package com.mcxx.modules.system.service.read;

import com.mcxx.common.exception.BizException;
import com.mcxx.constant.DictConstant;
import com.mcxx.modules.base.service.read.DictionaryReadService;
import com.mcxx.modules.filemanage.file.service.FileService;
import com.mcxx.modules.statistics.dao.read.AreaContrastReadDao;
import com.mcxx.modules.statistics.entity.AreaContrastEntity;
import com.mcxx.modules.statistics.entity.StatisticsExportEntity;
import com.mcxx.modules.statistics.entity.StatisticsExportItemEntity;
import com.mcxx.modules.system.dao.read.StatisticsExportItemReadDao;
import com.mcxx.modules.system.dao.read.StatisticsExportReadDao;
import com.mcxx.modules.system.param.StatisticsExportItemParam;
import com.mcxx.modules.system.service.write.StatisticsExportWriteService;
import com.mcxx.util.Constant;
import com.mcxx.util.DateUtil;
import com.yinhai.ta404.core.restservice.requestbean.PageParam;
import com.yinhai.ta404.core.restservice.resultbean.Page;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import com.yinhai.ta404.core.utils.ZipUtil;
import com.yinhai.ta404.module.dict.entity.TaDictPo;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
@TaTransactional
public class StatisticsExportItemReadService {

    @Autowired
    private StatisticsExportItemReadDao statisticsExportItemReadDao;
    @Autowired
    private FileService fileService;
    @Autowired
    private StatisticsExportWriteService statisticsExportWriteService;
    @Autowired
    private DictionaryReadService dictionaryReadService;
    @Autowired
    private AreaContrastReadDao areaContrastReadDao;
    @Autowired
    private StatisticsExportReadDao statisticsExportReadDao;

    private final String tmpdir = System.getProperty("java.io.tmpdir");
    private final String separator = System.getProperty("file.separator");


    public Page getPage(StatisticsExportItemParam statisticsExportItemParam, PageParam pageParam){
        statisticsExportItemReadDao.beginPager(pageParam);
        List<StatisticsExportItemEntity>  list = null;
        if(Constant.GuicaiType.CITY_DIBAO.equals(statisticsExportItemParam.getObjectType())){

            list = statisticsExportItemReadDao.listCityDibaoStatistics(statisticsExportItemParam);
        }else if(Constant.GuicaiType.COUNTY_DIBAO.equals(statisticsExportItemParam.getObjectType())){

            list = statisticsExportItemReadDao.listCountyDibaoStatistics(statisticsExportItemParam);
        }else if(Constant.GuicaiType.CITY_TEKUN.equals(statisticsExportItemParam.getObjectType())){

            list = statisticsExportItemReadDao.listCityTekunStatistics(statisticsExportItemParam);
        }else if(Constant.GuicaiType.COUNTY_TEKUN.equals(statisticsExportItemParam.getObjectType())){

            list = statisticsExportItemReadDao.listCountyTekunStatistics(statisticsExportItemParam);
        }else if(Constant.GuicaiType.TEMPORARY.equals(statisticsExportItemParam.getObjectType())){

            list = statisticsExportItemReadDao.listTemporaryStatistics(statisticsExportItemParam);
        }else{
            throw  new BizException("-1","参数异常");
        }
        return statisticsExportItemReadDao.endPager(list);
    }


    public void generateExportTxt(HttpServletResponse response, String statisticsId, String objectType){
        List<Map<String, Object>> statisticsExportItemList = new ArrayList<>();
        String title = "";
        String fileName = "";
        StatisticsExportEntity main = statisticsExportReadDao.getById(statisticsId);
        String aa = main.getYears();
        Date date = DateUtil.str2Date(aa, DateUtil.sdf2);
        Integer mos = date.getMonth()+1;
        String month = mos.toString().length() > 1 ? mos.toString() : "0"+mos.toString();
        if(Constant.GuicaiType.CITY_DIBAO.equals(objectType)){

            statisticsExportItemList = this.statisticsExportItemReadDao.getExportData11001(statisticsId);
            for(Map<String,Object>map:statisticsExportItemList){
                String f127 = map.get("F1_27")==null?"":String.valueOf(map.get("F1_27"));
                TaDictPo taDictPo = dictionaryReadService.getCodeCache(DictConstant.BANK_NAME,f127);
                map.put("F1_27", taDictPo.getLabel());
                String QYDM = map.get("_QYDM")==null?"":String.valueOf(map.get("_QYDM"));
                String qydm = getQydm(QYDM, month);
                map.put("_QYDM", qydm);
            }
            title = "_QYDM\tF1_1\tF1_2\tF1_3\tF1_4\tF1_5\tF1_6\tF1_7\tF1_8\tF1_9\tF1_10\tF1_11\tF1_12\tF1_13\tF1_61\t"
                    + "F1_15\tF1_16\tF1_17\tF1_18\tF1_19\tF1_20\tF1_22\tF1_23\tF1_24\tF1_25\tF1_26\tF1_27\tF1_28\t"
                    + "F1_29\tF1_30\tF1_60\tF1_40\tF1_41\tF1_42\tF1_43\tF1_44\tF1_45\tF1_46\tF1_47\tF1_48\tF1_49\t"
                    + "F1_50\tF1_51\tF1_52\tF1_53\tF1_54\tF1_55\tF1_56\tF1_57\tFLD_1\tF1_31";
            fileName = "T204_F3.txt";
        }else if(Constant.GuicaiType.COUNTY_DIBAO.equals(objectType)){

            statisticsExportItemList = this.statisticsExportItemReadDao.getExportData11002(statisticsId);
            for(Map<String,Object>map:statisticsExportItemList){
                String f123 = map.get("F1_23")==null?"":String.valueOf(map.get("F1_23"));
                TaDictPo taDictPo = dictionaryReadService.getCodeCache(DictConstant.BANK_NAME,f123);
                map.put("F1_23", taDictPo.getLabel());
                String QYDM = map.get("_QYDM")==null?"":String.valueOf(map.get("_QYDM"));
                String qydm = getQydm(QYDM, month);
                map.put("_QYDM", qydm);
            }
            title = "_QYDM\tF1_1\tF1_2\tF1_3\tF1_4\tF1_5\tF1_6\tF1_7\tF1_8\tF1_9\tF1_11\tF1_13\tF1_16\tF1_63\tF1_64\t"
                    + "F1_14\tF1_12\tF1_15\tF1_61\tF1_62\tF1_17\tF1_18\tF1_19\tF1_20\tF1_21\tF1_23\tF1_24\tF1_25\t"
                    + "F1_26\tF1_60\tF1_40\tF1_41\tF1_42\tF1_43\tF1_44\tF1_45\tF1_46\tF1_47\tF1_48\tF1_49\tF1_50\t"
                    + "F1_51\tF1_52\tF1_53\tF1_54\tF1_55\tF1_56\tF1_57\tFLD_1\tF1_27";
            fileName = "T205_F4.txt";
        }else if(Constant.GuicaiType.CITY_TEKUN.equals(objectType)){

            statisticsExportItemList = this.statisticsExportItemReadDao.getExportData13003(statisticsId);
            for(Map<String,Object>map:statisticsExportItemList){
                String f123 = map.get("F1_23")==null?"":String.valueOf(map.get("F1_23"));
                TaDictPo taDictPo = dictionaryReadService.getCodeCache(DictConstant.BANK_NAME,f123);
                map.put("F1_23", taDictPo.getLabel());
                String QYDM = map.get("_QYDM")==null?"":String.valueOf(map.get("_QYDM"));
                String qydm = getQydm(QYDM, month);
                map.put("_QYDM", qydm);
            }
            title = "_QYDM\tF1_1\tF1_2\tF1_3\tF1_4\tF1_5\tF1_6\tF1_7\tF1_8\tF1_9\tF1_10\tF1_11\tF1_12\tF1_13\tF1_14\tF1_15\t"
                    + "F1_16\tF1_70\tF1_71\tF1_72\tF1_17\tF1_18\tF1_19\tF1_20\tF1_21\tF1_22\tF1_23\tF1_24\tF1_25\tF1_26\t"
                    + "F1_60\tF1_40\tF1_41\tF1_42\tF1_43\tF1_44\tF1_45\tF1_46\tF1_47\tF1_48\tF1_49\tF1_50\tF1_51\tF1_52\t"
                    + "F1_53\tF1_54\tF1_55\tF1_56\tF1_57\tFLD_1\tF1_27";
            fileName = "T206_F4.txt";
        }else if(Constant.GuicaiType.COUNTY_TEKUN.equals(objectType)){

            statisticsExportItemList = this.statisticsExportItemReadDao.getExportData13004(statisticsId);
            for(Map<String,Object>map:statisticsExportItemList){
                String f123 = map.get("F1_23")==null?"":String.valueOf(map.get("F1_23"));
                TaDictPo taDictPo = dictionaryReadService.getCodeCache(DictConstant.BANK_NAME,f123);
                map.put("F1_23", taDictPo.getLabel());
                String QYDM = map.get("_QYDM")==null?"":String.valueOf(map.get("_QYDM"));
                String qydm = getQydm(QYDM, month);
                map.put("_QYDM", qydm);
            }
            title = "_QYDM\tF1_1\tF1_2\tF1_3\tF1_4\tF1_5\tF1_6\tF1_7\tF1_8\tF1_9\tF1_10\tF1_11\tF1_13\tF1_28\tF1_14"
                    + "\tF1_12\tF1_15\tF1_70\tF1_71\tF1_72\tF1_16\tF1_17\tF1_18\tF1_19\tF1_20\tF1_21\tF1_23\tF1_24\t"
                    + "F1_25\tF1_26\tF1_60\tF1_40\tF1_41\tF1_42\tF1_43\tF1_44\tF1_45\tF1_46\tF1_47\tF1_48\tF1_49\t"
                    + "F1_50\tF1_51\tF1_52\tF1_53\tF1_54\tF1_55\tF1_56\tF1_57\tFLD_1\tF1_27";
            fileName = "T207_F4.txt";
        }else{

            statisticsExportItemList = this.statisticsExportItemReadDao.getExportData500(statisticsId);
            for(Map<String,Object>map:statisticsExportItemList){
                String QYDM = map.get("_QYDM")==null?"":String.valueOf(map.get("_QYDM"));
                String qydm = getQydm(QYDM, month);
                map.put("_QYDM", qydm);
            }
            title = "_QYDM\tF1_3\tF1_2\tF1_7\tF1_8\tF1_9\tF1_11\tF1_6\tF1_12\tF1_13\tF1_1\tF1_14\tF1_15\tF1_25\tF1_26\tF1_27\tF1_16\tF1_17\tF1_18\tF1_19\tF1_20\tF1_21\tF1_22\tF1_23\tF1_24\t"
                    + "F1_28\tF1_29\tF1_30\tF1_31\tF1_32\tF1_33\tF1_34\tF1_35\tF1_36\tF1_37\tFLD_1";
            fileName = "T225_F2.txt";
        }

        String fileObjectId = this.writeTxt(response, fileName, title, statisticsExportItemList);


        StatisticsExportEntity statisticsExport = new StatisticsExportEntity();
        statisticsExport.setId(statisticsId);
        statisticsExport.setFilename(fileObjectId);
        this.statisticsExportWriteService.updateIgnoreNull(statisticsExport);
    }

    private String getQydm(String areaCode,String month) {
        String toAreaCode = "";
        AreaContrastEntity jcEntity = areaContrastReadDao.getByMcCode(areaCode);
        if (null != jcEntity) {
            toAreaCode = jcEntity.getJqAreaCode();

        }else{
            toAreaCode = areaCode;
        }
        toAreaCode = toAreaCode.substring(0, 9) + "999";
        toAreaCode += month + "7";
        return toAreaCode;
    }


    public String writeTxt(HttpServletResponse response, String fileName, String title, List<Map<String, Object>> statisticsExportItemList){
        String path = tmpdir+separator+fileName;
        FileOutputStream fileOutputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        StringBuffer content;
        try {

            File tmpFile = new File(path);
            if (!tmpFile.getParentFile().exists()){
                tmpFile.getParentFile().mkdirs();
            }
            tmpFile = new File(path);
            fileOutputStream = new FileOutputStream(tmpFile);
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

            bufferedOutputStream.write(title.getBytes("GB18030"));
            bufferedOutputStream.write("\r\n".getBytes("GB18030"));
            String [] column = title.split("\t");
            int columnNumber = column.length;

            for (Map<String, Object> item : statisticsExportItemList) {
                content = new StringBuffer();
                for(int i=0;i<column.length;i++){
                    String columnName = column[i];
                    String columnContent = item.get(columnName)==null?"":String.valueOf(item.get(columnName));
                    if(i<(columnNumber-1)){
                        content.append(columnContent).append("\t");
                    }
                }
                content.append("\r\n");
                bufferedOutputStream.write(content.toString().getBytes("GB18030"));
            }
            bufferedOutputStream.flush();
            bufferedOutputStream.close();


            InputStream inputStream = new FileInputStream(tmpFile);
            byte[] bytes = IOUtils.toByteArray(inputStream);

            File zipFile = ZipUtil.compressFileForObject(tmpFile.getName(), bytes);
            FileInputStream input = new FileInputStream(zipFile);
            String objectKey = fileService.upload(input,zipFile.getName());
            zipFile.delete();
            tmpFile.delete();
            return objectKey;
        } catch (Exception e) {
           throw new BizException("-1", "文件服务器存在异常，无法上传文件");
        } finally {
            try {
                bufferedOutputStream.close();
                fileOutputStream.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
